#![allow(dead_code)]

struct FileLrn {}

impl FileLrn {
    pub fn hello() {
        println!("Fs learning!");
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs::OpenOptions,
        io::{Read, Write},
    };

    #[test]
    /// 创建文件
    fn test_create() -> std::io::Result<()> {
        let sentence = String::from("hello world!");
        let mut file = std::fs::File::create("./src/fs_lrn/create.txt")?;
        file.write_all(b"try to create\n")?;
        file.write_all(sentence.as_bytes()).expect("fail to write!");
        println!("创建文件成功 {:?}", file);
        Ok(())
    }

    #[test]
    /// 打开文件
    fn test_open() {
        let file = std::fs::File::open("./src/fs_lrn/create.txt").expect("fail to open!");
        println!("文件打开成功 {:?}", file);
    }

    #[test]
    /// 读取文件
    ///
    /// read() 读取未vector
    /// read_to_end(),
    /// read_to_string() 读取为字符串
    fn test_read() {
        let mut file = std::fs::File::open("./src/fs_lrn/foo.txt").unwrap();
        let mut contents = String::new();
        file.read_to_string(&mut contents).unwrap();
        println!("{}", contents);
    }

    #[test]
    /// 写入文件
    ///
    /// write(), write_all()
    /// 把一个切片写入文件，如果文件不存在就会创建文件，如果文件存在就替换其内容。
    fn test_write() {
        std::fs::write("./src/fs_lrn/write.txt", "write mothod\n").unwrap();
        println!("file created!");
    }

    #[test]
    /// 删除文件
    fn test_remove_file() {
        std::fs::remove_file("./src/fs_lrn/write.txt").expect("can not remove file");
        println!("file is removed!");
    }

    #[test]
    /// 追加文件
    /// OpenOptions::new().append(true).open().expect();
    fn test_append() {
        let mut file = OpenOptions::new()
            .append(true)
            .open("./src/fs_lrn/foo.txt")
            .expect("can not open!");
        file.write_all(b"\nadd something at the end of article!")
            .expect("fail to append");
    }
}
